package com.itqiqi.api.tableapi.udf;

import com.itqiqi.api.pojo.SensorReading;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.java.StreamTableEnvironment;
import org.apache.flink.table.functions.ScalarFunction;
import org.apache.flink.table.functions.TableFunction;
import org.apache.flink.types.Row;

public class UdfTest2_TableFunction {

    public static void main(String[] args) throws Exception {

        // 创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // 创建表环境
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        // 读取数据
        DataStreamSource<String> inputStream = env.readTextFile("input/sensor.txt");

        SingleOutputStreamOperator<SensorReading> dataStream = inputStream.map(new MapFunction<String, SensorReading>() {
            @Override
            public SensorReading map(String s) throws Exception {
                String[] words = s.split(",");
                return new SensorReading(words[0], new Long(words[1]), new Double(words[2]));
            }
        });

        // 将流转换成表
        Table sensorTable = tableEnv.fromDataStream(dataStream, "id, timestamp as ts, temperature as temp");

        // TODO: 2022/5/19 自定义表函数，实现将id拆分，并输出（word,length）
        // 在环境中注册UDF
        Split split = new Split("_");
        tableEnv.registerFunction("split", split);

        // table API
        Table resTable = sensorTable
                .joinLateral("split(id) as (word, length)")
                .select("id, ts, word, length");

        // SQL
        tableEnv.createTemporaryView("sensorTable", sensorTable);
        Table sqlTable = tableEnv.sqlQuery("select id, ts, word, length" +
                " from sensorTable, lateral table(split(id)) as splitid(word, length)");

        // 输出结果
        sensorTable.printSchema();
        tableEnv.toAppendStream(resTable, Row.class).print("resTable");
        tableEnv.toAppendStream(sqlTable, Row.class).print("sqlTable");

        env.execute();
    }

    // TODO: 2022/5/19 实现自定义的 Table Function
    public static class Split extends TableFunction<Tuple2<String, Integer>> {

        private String separator = ",";

        public Split(String separator) {
            this.separator = separator;
        }

        public void eval(String str) {
            for (String s : str.split(separator)) {
                collect(new Tuple2<>(s, s.length()));
            }
        }
    }
}
